import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import Header from './Header';
import PhotoPreview from './PhotoPreview';
import './SocialFeed.css';

const SocialFeed = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(true);
  const [posts, setPosts] = useState([]);
  const [showCreatePost, setShowCreatePost] = useState(false);
  const [newPost, setNewPost] = useState({
    text: '',
    photos: [],
    location: '',
    mood: ''
  });
  const [showComments, setShowComments] = useState({});
  const [newComments, setNewComments] = useState({});
  const [showLocationSuggestions, setShowLocationSuggestions] = useState(false);
  const [postComments, setPostComments] = useState({});
  const [showPhotoPreview, setShowPhotoPreview] = useState(false);
  const [previewPhotos, setPreviewPhotos] = useState([]);
  const [currentPhotoIndex, setCurrentPhotoIndex] = useState(0);
  const [showEmojiPicker, setShowEmojiPicker] = useState({});
  const [commentPhotos, setCommentPhotos] = useState({});

  // Helper function to determine grid class based on photo count
  const getPhotoGridClass = (photoCount) => {
    if (photoCount === 1) return 'single';
    if (photoCount === 2) return 'two';
    if (photoCount === 3) return 'three';
    if (photoCount === 4) return 'four';
    if (photoCount >= 5 && photoCount <= 6) return 'six';
    if (photoCount >= 7 && photoCount <= 9) return 'nine';
    return 'many'; // For more than 9 photos
  };

  // Helper function to determine individual photo class
  const getPhotoClass = (photoCount, index) => {
    if (photoCount === 3 && index === 2) return 'wide'; // Third photo in 3-photo layout spans full width
    if (photoCount === 5 && index >= 3) return 'small'; // Last 2 photos in 5-photo layout are smaller
    if (photoCount === 7 && index >= 5) return 'small'; // Last 2 photos in 7-photo layout are smaller
    if (photoCount > 9 && index === 8) return 'with-overlay'; // Ninth photo has overlay for "more photos"
    return '';
  };

  // Handle location selection from suggestions
  const handleLocationSelect = (location) => {
    setNewPost(prev => ({
      ...prev,
      location
    }));
    setShowLocationSuggestions(false);
  };

  // Get emoji for mood
  const getMoodEmoji = (mood) => {
    const moodEmojis = {
      '开心': '😊',
      '兴奋': '🤗',
      '平静': '😌',
      '有成就感': '🏆',
      '感动': '😭',
      '幸福': '😊',
      '满足': '😌',
      '期待': '🤗',
      '感激': '🙏',
      '放松': '😎',
      '思考': '🤔',
      '疲惫': '😴',
      '焦虑': '😰',
      '沮丧': '😔',
      '愤怒': '😠',
      '孤独': '🧐',
      '怀旧': '📜',
      '憧憬': '✨',
      '浪漫': '💕',
      '活力': '⚡',
      '创意': '💡'
    };
    return moodEmojis[mood] || '';
  };

  // Handle photo preview
  const handlePhotoClick = (photos, index) => {
    setPreviewPhotos(photos);
    setCurrentPhotoIndex(index);
    setShowPhotoPreview(true);
  };

  const closePhotoPreview = () => {
    setShowPhotoPreview(false);
    setPreviewPhotos([]);
    setCurrentPhotoIndex(0);
  };

  // Handle emoji selection for comments
  const toggleEmojiPicker = (postId) => {
    setShowEmojiPicker(prev => ({
      ...prev,
      [postId]: !prev[postId]
    }));
  };

  const addEmojiToComment = (postId, emoji) => {
    setNewComments(prev => ({
      ...prev,
      [postId]: (prev[postId] || '') + emoji
    }));
    setShowEmojiPicker(prev => ({
      ...prev,
      [postId]: false
    }));
  };

  // Handle photo upload for comments
  const handleCommentPhotoUpload = (postId, e) => {
    const files = Array.from(e.target.files);
    
    // Create promises to read each file as a data URL
    const filePromises = files.map((file, index) => {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = (event) => {
          resolve({
            id: Date.now() + index,
            name: file.name,
            thumbnail: event.target.result
          });
        };
        reader.readAsDataURL(file);
      });
    });
    
    // Wait for all files to be read
    Promise.all(filePromises).then(photoList => {
      setCommentPhotos(prev => ({
        ...prev,
        [postId]: [...(prev[postId] || []), ...photoList]
      }));
    });
  };

  const removeCommentPhoto = (postId, photoId) => {
    setCommentPhotos(prev => ({
      ...prev,
      [postId]: prev[postId].filter(photo => photo.id !== photoId)
    }));
  };

  // Check for mock authentication
  const isAuthenticated = !!localStorage.getItem('mockAuthToken');
  const user = isAuthenticated ? JSON.parse(localStorage.getItem('mockUser') || '{}') : null;

  useEffect(() => {
    // Simulate loading social feed data
    setTimeout(() => {
      const mockPosts = [
        {
          id: 1,
          author: {
            id: 101,
            name: '张小明',
            avatar: '👨‍💼',
            isCurrentUser: false
          },
          content: {
            text: '今天和朋友去了海边，看到了美丽的日落！生活就是这样，总有一些不期而遇的美好。#海边日落 #美好时光',
            photos: [
              { id: 1001, name: '海边日落.jpg', thumbnail: '🌅' },
              { id: 1002, name: '沙滩照片.jpg', thumbnail: '🏖️' }
            ],
            location: '青岛海滩',
            mood: '开心',
            timestamp: '2023-10-18 18:30'
          },
          interactions: {
            likes: 28,
            comments: 5,
            shares: 2,
            isLiked: false
          }
        },
        {
          id: 2,
          author: {
            id: 102,
            name: '李雨婷',
            avatar: '👩‍🎨',
            isCurrentUser: false
          },
          content: {
            text: '刚完成了一幅新的画作，分享给大家！艺术是生活的镜子，也是心灵的窗户。',
            photos: [
              { id: 2001, name: '画作.jpg', thumbnail: '🎨' }
            ],
            location: '工作室',
            mood: '有成就感',
            timestamp: '2023-10-18 16:45'
          },
          interactions: {
            likes: 42,
            comments: 8,
            shares: 3,
            isLiked: true
          }
        },
        {
          id: 3,
          author: {
            id: 103,
            name: '王大伟',
            avatar: '👨‍🍳',
            isCurrentUser: false
          },
          content: {
            text: '周末尝试做了一道新菜，味道还不错！分享给美食爱好者们！#美食分享 #周末下厨',
            photos: [
              { id: 3001, name: '美食.jpg', thumbnail: '🍲' },
              { id: 3002, name: '食材.jpg', thumbnail: '🥘' }
            ],
            location: '家中厨房',
            mood: '满足',
            timestamp: '2023-10-17 20:15'
          },
          interactions: {
            likes: 35,
            comments: 12,
            shares: 1,
            isLiked: false
          }
        }
      ];

      // Get user posts from localStorage
      const userPosts = JSON.parse(localStorage.getItem('userSocialPosts') || '[]');
      
      // Combine mock posts with user posts
      const allPosts = [...userPosts, ...mockPosts];
      
      // Sort by timestamp (newest first)
      allPosts.sort((a, b) => new Date(b.content.timestamp) - new Date(a.content.timestamp));
      
      setPosts(allPosts);
      
      // Initialize mock comments for posts
      const mockComments = {
        1: [
          { id: 1001, author: '李小红', text: '太美了！我也想去这里看日落', timestamp: '2023-10-18 19:00', isCurrentUser: false },
          { id: 1002, author: '王大明', text: '这是青岛哪里？看起来很棒', timestamp: '2023-10-18 19:15', isCurrentUser: false },
          { id: 1003, author: '赵小雨', text: '青岛的海边确实很美，推荐你去金沙滩', timestamp: '2023-10-18 19:30', isCurrentUser: false },
          { id: 1004, author: '刘小芳', text: '拍得真好，构图很棒', timestamp: '2023-10-18 20:00', isCurrentUser: false },
          { id: 1005, author: '陈小军', text: '下次一起去玩啊', timestamp: '2023-10-18 20:15', isCurrentUser: false }
        ],
        2: [
          { id: 2001, author: '艺术爱好者', text: '色彩搭配很有感觉', timestamp: '2023-10-18 17:00', isCurrentUser: false },
          { id: 2002, author: '画家小王', text: '这是什么风格的画？很有创意', timestamp: '2023-10-18 17:30', isCurrentUser: false },
          { id: 2003, author: '美术老师', text: '构图和色彩都很棒，继续加油', timestamp: '2023-10-18 18:00', isCurrentUser: false },
          { id: 2004, author: '学生小李', text: '老师，能教教我怎么画吗', timestamp: '2023-10-18 18:15', isCurrentUser: false },
          { id: 2005, author: '画廊老板', text: '有兴趣来我们画廊展出吗', timestamp: '2023-10-18 18:30', isCurrentUser: false },
          { id: 2006, author: '艺术评论家', text: '很有潜力的作品', timestamp: '2023-10-18 19:00', isCurrentUser: false },
          { id: 2007, author: '收藏家', text: '这幅画有收藏价值', timestamp: '2023-10-18 19:15', isCurrentUser: false },
          { id: 2008, author: '艺术系学生', text: '能分享一下创作过程吗', timestamp: '2023-10-18 19:30', isCurrentUser: false }
        ],
        3: [
          { id: 3001, author: '美食家', text: '看起来很好吃，能分享一下食谱吗', timestamp: '2023-10-17 20:30', isCurrentUser: false },
          { id: 3002, author: '厨师小李', text: '这个摆盘很专业', timestamp: '2023-10-17 21:00', isCurrentUser: false },
          { id: 3003, author: '家庭主妇', text: '周末也给孩子做这个', timestamp: '2023-10-17 21:15', isCurrentUser: false },
          { id: 3004, author: '美食博主', text: '能详细介绍一下做法吗', timestamp: '2023-10-17 21:30', isCurrentUser: false },
          { id: 3005, author: '营养师', text: '营养搭配很均衡', timestamp: '2023-10-17 22:00', isCurrentUser: false },
          { id: 3006, author: '餐厅老板', text: '有兴趣来我们餐厅交流吗', timestamp: '2023-10-17 22:15', isCurrentUser: false },
          { id: 3007, author: '吃货小王', text: '看着就流口水了', timestamp: '2023-10-17 22:30', isCurrentUser: false },
          { id: 3008, author: '烹饪爱好者', text: '火候掌握得很好', timestamp: '2023-10-17 22:45', isCurrentUser: false },
          { id: 3009, author: '美食摄影师', text: '拍得很有食欲', timestamp: '2023-10-17 23:00', isCurrentUser: false },
          { id: 3010, author: '食材供应商', text: '需要优质食材可以联系我', timestamp: '2023-10-17 23:15', isCurrentUser: false },
          { id: 3011, author: '美食评论家', text: '色香味俱全', timestamp: '2023-10-17 23:30', isCurrentUser: false },
          { id: 3012, author: '烹饪学校', text: '欢迎来我们学校学习', timestamp: '2023-10-17 23:45', isCurrentUser: false }
        ]
      };
      
      // Get user comments from localStorage
      const userComments = JSON.parse(localStorage.getItem('userSocialComments') || '{}');
      
      // Combine mock comments with user comments
      const allComments = { ...mockComments, ...userComments };
      
      setPostComments(allComments);
      setIsLoading(false);
    }, 1000);
  }, []);

  const handleCreatePost = () => {
    setShowCreatePost(true);
  };

  const handleCloseCreatePost = () => {
    setShowCreatePost(false);
    setNewPost({
      text: '',
      photos: [],
      location: '',
      mood: ''
    });
  };

  const handlePostInputChange = (e) => {
    const { name, value } = e.target;
    setNewPost(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handlePhotoUpload = (e) => {
    const files = Array.from(e.target.files);
    
    // Create promises to read each file as a data URL
    const filePromises = files.map((file, index) => {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = (event) => {
          resolve({
            id: Date.now() + index,
            name: file.name,
            thumbnail: event.target.result
          });
        };
        reader.readAsDataURL(file);
      });
    });
    
    // Wait for all files to be read
    Promise.all(filePromises).then(photoList => {
      setNewPost(prev => ({
        ...prev,
        photos: [...prev.photos, ...photoList]
      }));
    });
  };

  const handleRemovePhoto = (photoId) => {
    setNewPost(prev => ({
      ...prev,
      photos: prev.photos.filter(photo => photo.id !== photoId)
    }));
  };

  const handleSubmitPost = () => {
    if (!newPost.text.trim() && newPost.photos.length === 0) {
      alert(t('social.emptyPost'));
      return;
    }

    // Create a new post
    const post = {
      id: Date.now(),
      author: {
        id: user.id,
        name: user.name,
        avatar: user.name.charAt(0).toUpperCase(),
        isCurrentUser: true
      },
      content: {
        text: newPost.text,
        photos: newPost.photos,
        location: newPost.location,
        mood: newPost.mood,
        timestamp: new Date().toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      },
      interactions: {
        likes: 0,
        comments: 0,
        shares: 0,
        isLiked: false
      }
    };

    // Add the new post to the posts list
    const updatedPosts = [post, ...posts];
    setPosts(updatedPosts);
    
    // Save to localStorage
    localStorage.setItem('userSocialPosts', JSON.stringify(
      updatedPosts.filter(p => p.author.isCurrentUser)
    ));
    
    // Close the modal and reset form
    handleCloseCreatePost();
  };

  const handleLikePost = (postId) => {
    const updatedPosts = posts.map(post => {
      if (post.id === postId) {
        return {
          ...post,
          interactions: {
            ...post.interactions,
            likes: post.interactions.isLiked ? post.interactions.likes - 1 : post.interactions.likes + 1,
            isLiked: !post.interactions.isLiked
          }
        };
      }
      return post;
    });
    
    setPosts(updatedPosts);
    
    // Update localStorage for user posts
    const userPosts = updatedPosts.filter(p => p.author.isCurrentUser);
    localStorage.setItem('userSocialPosts', JSON.stringify(userPosts));
  };

  const handleSharePost = (postId) => {
    const updatedPosts = posts.map(post => {
      if (post.id === postId) {
        return {
          ...post,
          interactions: {
            ...post.interactions,
            shares: post.interactions.shares + 1
          }
        };
      }
      return post;
    });
    
    setPosts(updatedPosts);
    
    // Update localStorage for user posts
    const userPosts = updatedPosts.filter(p => p.author.isCurrentUser);
    localStorage.setItem('userSocialPosts', JSON.stringify(userPosts));
    
    alert(t('social.postShared'));
  };

  const toggleComments = (postId) => {
    setShowComments(prev => ({
      ...prev,
      [postId]: !prev[postId]
    }));
  };

  const handleCommentChange = (postId, value) => {
    setNewComments(prev => ({
      ...prev,
      [postId]: value
    }));
  };

  const handleAddComment = (postId) => {
    const commentText = newComments[postId] || '';
    const photos = commentPhotos[postId] || [];
    
    if (commentText.trim() === '' && photos.length === 0) return;

    // Create a new comment
    const newComment = {
      id: Date.now(),
      author: user.name,
      text: commentText.trim(),
      photos: photos,
      timestamp: new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      }),
      isCurrentUser: true
    };

    // Update comments for the post
    const updatedComments = {
      ...postComments,
      [postId]: [...(postComments[postId] || []), newComment]
    };
    
    setPostComments(updatedComments);
    
    // Update posts comment count
    const updatedPosts = posts.map(post => {
      if (post.id === postId) {
        return {
          ...post,
          interactions: {
            ...post.interactions,
            comments: post.interactions.comments + 1
          }
        };
      }
      return post;
    });
    
    setPosts(updatedPosts);
    
    // Clear the comment input and photos
    setNewComments(prev => ({
      ...prev,
      [postId]: ''
    }));
    
    setCommentPhotos(prev => ({
      ...prev,
      [postId]: []
    }));
    
    // Save to localStorage
    localStorage.setItem('userSocialComments', JSON.stringify(updatedComments));
    
    // Update localStorage for user posts
    const userPosts = updatedPosts.filter(p => p.author.isCurrentUser);
    localStorage.setItem('userSocialPosts', JSON.stringify(userPosts));
  };

  if (!isAuthenticated) {
    navigate('/auth');
    return null;
  }

  return (
    <div className="social-feed-container">
      <Header />
      <div className="social-feed-content">
        <div className="social-feed-header">
          <h1 className="social-feed-title">{t('social.title')}</h1>
          <p className="social-feed-subtitle">{t('social.subtitle')}</p>
        </div>

        {/* Create Post Button */}
        <div className="create-post-section">
          <div className="create-post-prompt" onClick={handleCreatePost}>
            <div className="user-avatar-small">{user.name.charAt(0).toUpperCase()}</div>
            <div className="create-post-input-placeholder">{t('social.whatsOnYourMind')}</div>
          </div>
        </div>

        {/* Create Post Modal */}
        {showCreatePost && (
          <div className="modal-overlay">
            <div className="create-post-modal">
              <div className="modal-header">
                <h2>{t('social.createPost')}</h2>
                <button className="close-btn" onClick={handleCloseCreatePost}>×</button>
              </div>
              <div className="create-post-content">
                <div className="post-author">
                  <div className="user-avatar-small">{user.name.charAt(0).toUpperCase()}</div>
                  <div className="author-name">{user.name}</div>
                </div>
                
                <textarea
                  name="text"
                  value={newPost.text}
                  onChange={handlePostInputChange}
                  placeholder={t('social.shareYourThoughts')}
                  className="post-text-input"
                  rows={4}
                />
                
                <div className="post-options">
                  <div className="post-option">
                    <label>{t('social.location')}</label>
                    <div className="location-input-wrapper">
                      <input
                        type="text"
                        name="location"
                        value={newPost.location}
                        onChange={handlePostInputChange}
                        placeholder={t('social.addLocation')}
                        className="post-option-input"
                      />
                      <button
                        type="button"
                        className="location-suggestions-btn"
                        onClick={() => setShowLocationSuggestions(!showLocationSuggestions)}
                      >
                        📍
                      </button>
                    </div>
                    {showLocationSuggestions && (
                      <div className="location-suggestions">
                        <div
                          className="location-suggestion"
                          onClick={() => handleLocationSelect('北京·三里屯')}
                        >
                          🏙️ 北京·三里屯
                        </div>
                        <div
                          className="location-suggestion"
                          onClick={() => handleLocationSelect('上海·外滩')}
                        >
                          🌃 上海·外滩
                        </div>
                        <div
                          className="location-suggestion"
                          onClick={() => handleLocationSelect('深圳·南山')}
                        >
                          🏢 深圳·南山
                        </div>
                        <div
                          className="location-suggestion"
                          onClick={() => handleLocationSelect('杭州·西湖')}
                        >
                          🏞️ 杭州·西湖
                        </div>
                        <div
                          className="location-suggestion"
                          onClick={() => handleLocationSelect('成都·春熙路')}
                        >
                          🍜 成都·春熙路
                        </div>
                        <div
                          className="location-suggestion"
                          onClick={() => handleLocationSelect('广州·珠江新城')}
                        >
                          🌉 广州·珠江新城
                        </div>
                        <div
                          className="location-suggestion"
                          onClick={() => handleLocationSelect('家中')}
                        >
                          🏠 家中
                        </div>
                        <div
                          className="location-suggestion"
                          onClick={() => handleLocationSelect('旅行中')}
                        >
                          ✈️ 旅行中
                        </div>
                      </div>
                    )}
                  </div>
                  
                  <div className="post-option">
                    <label>{t('social.mood')}</label>
                    <div className="mood-selection">
                      <select
                        name="mood"
                        value={newPost.mood}
                        onChange={handlePostInputChange}
                        className="post-option-select"
                      >
                        <option value="">{t('social.selectMood')}</option>
                        <option value="开心">{t('social.happy')}</option>
                        <option value="兴奋">{t('social.excited')}</option>
                        <option value="平静">{t('social.calm')}</option>
                        <option value="有成就感">{t('social.accomplished')}</option>
                        <option value="感动">{t('social.moved')}</option>
                        <option value="幸福">😊 幸福</option>
                        <option value="满足">😌 满足</option>
                        <option value="期待">🤗 期待</option>
                        <option value="感激">🙏 感激</option>
                        <option value="放松">😎 放松</option>
                        <option value="思考">🤔 思考</option>
                        <option value="疲惫">😴 疲惫</option>
                        <option value="焦虑">😰 焦虑</option>
                        <option value="沮丧">😔 沮丧</option>
                        <option value="愤怒">😠 愤怒</option>
                        <option value="孤独">🧐 孤独</option>
                        <option value="怀旧">📜 怀旧</option>
                        <option value="憧憬">✨ 憧憬</option>
                        <option value="浪漫">💕 浪漫</option>
                        <option value="活力">⚡ 活力</option>
                        <option value="创意">💡 创意</option>
                      </select>
                      <div className="mood-emoji-display">
                        {getMoodEmoji(newPost.mood)}
                      </div>
                    </div>
                  </div>
                </div>
                
                <div className="post-photos-section">
                  <div className="upload-photos-btn">
                    <input
                      type="file"
                      id="post-photo-upload"
                      multiple
                      accept="image/*"
                      onChange={handlePhotoUpload}
                      style={{ display: 'none' }}
                    />
                    <label htmlFor="post-photo-upload" className="upload-photos-label">
                      📷 {t('social.addPhotos')}
                    </label>
                  </div>
                  
                  {newPost.photos.length > 0 && (
                    <div className="uploaded-photos">
                      {newPost.photos.map(photo => (
                        <div key={photo.id} className="uploaded-photo">
                          {photo.thumbnail.startsWith('data:') ? (
                            <img src={photo.thumbnail} alt={photo.name} />
                          ) : (
                            <span>{photo.thumbnail}</span>
                          )}
                          <button 
                            className="remove-photo-btn" 
                            onClick={() => handleRemovePhoto(photo.id)}
                          >
                            ×
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
              
              <div className="modal-actions">
                <button type="button" className="cancel-btn" onClick={handleCloseCreatePost}>
                  {t('albums.cancel')}
                </button>
                <button type="button" className="post-btn" onClick={handleSubmitPost}>
                  {t('social.post')}
                </button>
              </div>
            </div>
          </div>
        )}

        {isLoading ? (
          <div className="social-feed-loading">
            <div className="loading-spinner"></div>
            <p>{t('social.loading')}</p>
          </div>
        ) : (
          <div className="social-feed-posts">
            {posts.length > 0 ? (
              posts.map(post => (
                <div key={post.id} className="social-post">
                  <div className="post-header">
                    <div className="post-author-info">
                      <div className="author-avatar">{post.author.avatar}</div>
                      <div className="author-details">
                        <div className="author-name">{post.author.name}</div>
                        <div className="post-timestamp">{post.content.timestamp}</div>
                      </div>
                    </div>
                    {post.content.location && (
                      <div className="post-location">📍 {post.content.location}</div>
                    )}
                  </div>
                  
                  <div className="post-content">
                    {post.content.text && (
                      <div className="post-text">{post.content.text}</div>
                    )}
                    
                    {post.content.photos.length > 0 && (
                      <div className={`post-photos ${getPhotoGridClass(post.content.photos.length)}`}>
                        {post.content.photos.slice(0, 9).map((photo, index) => (
                          <div
                            key={photo.id}
                            className={`post-photo ${getPhotoClass(post.content.photos.length, index)}`}
                            onClick={() => handlePhotoClick(post.content.photos, index)}
                          >
                            {photo.thumbnail.startsWith('data:') ? (
                              <img src={photo.thumbnail} alt={photo.name} />
                            ) : (
                              <span className="photo-emoji">{photo.thumbnail}</span>
                            )}
                            {post.content.photos.length > 9 && index === 8 && (
                              <div className="more-photos-overlay">
                                <div className="more-photos-text">
                                  +{post.content.photos.length - 9}
                                </div>
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                    )}
                    
                    {post.content.mood && (
                      <div className="post-mood">
                        {t('social.moodLabel')}: {post.content.mood}
                      </div>
                    )}
                  </div>
                  
                  <div className="post-interactions">
                    <div className="interaction-buttons">
                      <button 
                        className={`interaction-btn ${post.interactions.isLiked ? 'liked' : ''}`}
                        onClick={() => handleLikePost(post.id)}
                      >
                        {post.interactions.isLiked ? '❤️' : '🤍'} {post.interactions.likes}
                      </button>
                      
                      <button 
                        className="interaction-btn"
                        onClick={() => toggleComments(post.id)}
                      >
                        💬 {post.interactions.comments}
                      </button>
                      
                      <button 
                        className="interaction-btn"
                        onClick={() => handleSharePost(post.id)}
                      >
                        🔄 {post.interactions.shares}
                      </button>
                    </div>
                  </div>
                  
                  {showComments[post.id] && (
                    <div className="post-comments">
                      <div className="add-comment">
                        <div className="comment-input-container">
                          <input
                            type="text"
                            value={newComments[post.id] || ''}
                            onChange={(e) => handleCommentChange(post.id, e.target.value)}
                            placeholder={t('social.addComment')}
                            className="comment-input"
                            onKeyPress={(e) => e.key === 'Enter' && handleAddComment(post.id)}
                          />
                          <div className="comment-input-actions">
                            <button
                              className="comment-action-btn emoji-btn"
                              onClick={() => toggleEmojiPicker(post.id)}
                              title="添加表情"
                            >
                              😊
                            </button>
                            <label className="comment-action-btn photo-btn" title="添加图片">
                              📷
                              <input
                                type="file"
                                accept="image/*"
                                multiple
                                onChange={(e) => handleCommentPhotoUpload(post.id, e)}
                                style={{ display: 'none' }}
                              />
                            </label>
                          </div>
                        </div>
                        
                        {/* Emoji Picker */}
                        {showEmojiPicker[post.id] && (
                          <div className="emoji-picker">
                            <div className="emoji-grid">
                              {['😊', '😂', '❤️', '👍', '🎉', '😍', '🤔', '😎', '😭', '😡', '👏', '🙏', '💪', '🔥', '✨', '💯', '🎁', '🌹', '🌈', '☕'].map(emoji => (
                                <span
                                  key={emoji}
                                  className="emoji-item"
                                  onClick={() => addEmojiToComment(post.id, emoji)}
                                >
                                  {emoji}
                                </span>
                              ))}
                            </div>
                          </div>
                        )}
                        
                        {/* Comment Photos Preview */}
                        {commentPhotos[post.id] && commentPhotos[post.id].length > 0 && (
                          <div className="comment-photos-preview">
                            {commentPhotos[post.id].map(photo => (
                              <div key={photo.id} className="comment-photo-preview">
                                <img src={photo.thumbnail} alt={photo.name} />
                                <button
                                  className="remove-comment-photo-btn"
                                  onClick={() => removeCommentPhoto(post.id, photo.id)}
                                >
                                  ×
                                </button>
                              </div>
                            ))}
                          </div>
                        )}
                        
                        <button
                          className="comment-submit-btn"
                          onClick={() => handleAddComment(post.id)}
                        >
                          {t('social.post')}
                        </button>
                      </div>
                      
                      {/* Display actual comments */}
                      {postComments[post.id] && postComments[post.id].length > 0 && (
                        <div className="comments-list">
                          {postComments[post.id].map(comment => (
                            <div key={comment.id} className={`comment-item ${comment.isCurrentUser ? 'current-user' : ''}`}>
                              <div className="comment-author">
                                {comment.isCurrentUser ? (
                                  <span className="author-name current-user-name">{comment.author}</span>
                                ) : (
                                  <span className="author-name">{comment.author}</span>
                                )}
                                <span className="comment-timestamp">{comment.timestamp}</span>
                              </div>
                              {comment.text && <div className="comment-text">{comment.text}</div>}
                              {comment.photos && comment.photos.length > 0 && (
                                <div className="comment-photos">
                                  {comment.photos.map(photo => (
                                    <img
                                      key={photo.id}
                                      src={photo.thumbnail}
                                      alt={photo.name}
                                      className="comment-photo"
                                      onClick={() => handlePhotoClick([photo], 0)}
                                    />
                                  ))}
                                </div>
                              )}
                            </div>
                          ))}
                        </div>
                      )}
                      
                    </div>
                  )}
                </div>
              ))
            ) : (
              <div className="no-posts">
                <div className="no-posts-icon">📝</div>
                <h3>{t('social.noPosts')}</h3>
                <p>{t('social.noPostsMessage')}</p>
              </div>
            )}
          </div>
        )}
      </div>
      
      {/* Photo Preview Modal */}
      {showPhotoPreview && (
        <PhotoPreview
          photos={previewPhotos}
          currentIndex={currentPhotoIndex}
          onClose={closePhotoPreview}
        />
      )}
    </div>
  );
};

export default SocialFeed;